package linkedlist.pro;

import linkedlist.ListNode;

/**
 * @Classname : OddEvenLinkedList
 * @Description :
 * <a href="https://leetcode.cn/problems/odd-even-linked-list/">328. 奇偶链表</a>
 * @Author : chentianyu
 * @Date 2022/12/26 22:22
 */


public class OddEvenLinkedList {
    public ListNode oddEvenList(ListNode head) {
        ListNode evenHead = null, oddHead = null, evenTail = null, oddTail = null;
        int i = 1;
        while (head != null) {
            if (i % 2 == 1) {
                if (evenHead == null) evenHead = head;
                if (evenTail != null) evenTail.next = head;
                evenTail = head;
            }
            else {
                if (oddHead == null) oddHead = head;
                if (oddTail != null) oddTail.next = head;
                oddTail = head;
            }
            head = head.next;
            i++;
        }
        if (evenTail != null) evenTail.next = oddHead;
        if (oddTail != null) oddTail.next = null;
        return evenHead;
    }
}
